package com.eastsunsoft.swordfish.cms.common;

import com.eastsunsoft.swordfish.common.ApiConstant;
import com.eastsunsoft.swordfish.common.ResJson;
import com.eastsunsoft.swordfish.common.SwordfishException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * GlobalExceptionHandler
 *
 * @author donny
 * @date 8/31/16
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = SwordfishException.class)
    @ResponseBody
    public ResJson SwordfishExceptionHandler(SwordfishException e) {
        LOGGER.error("接口调用出错！" + e.getMessage(), e);
        ResJson r = new ResJson();
        String[] res = e.getMessage().split(":");
        buildRes(r, res);

        return r;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResJson exceptionHandler(Exception e) {
        LOGGER.error("接口调用出错！" + e.getMessage(), e);
        ResJson r = new ResJson();

        r.setErrcode(Integer.valueOf(ApiConstant.ERRCODE_EXCEPTION));
        r.setMsg(e.getMessage());

        return r;
    }

    private void buildRes(ResJson r, String[] res) {
        if (res.length != 2) {
            r.setErrcode(-2);
            r.setMsg("Unknown Error!");
        } else {
            r.setErrcode(Integer.valueOf(res[0]));
            r.setMsg(res[1]);
        }
    }
}